package ru.edu.vstu.atpp.acm.ui.security;

import org.apache.tapestry5.Link;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.*;
import ru.edu.vstu.atpp.acm.annotation.LoggedInUserAccess;
import ru.edu.vstu.atpp.acm.ui.pages.AccessErrorPage;
import ru.edu.vstu.atpp.acm.ui.services.authenticator.Authenticator;

import java.io.IOException;

/**
 * Фильтр проверяющий что пользователь авторизирован в системе
 */
public class AuthenticationFilter implements ComponentRequestFilter {

    private final PageRenderLinkSource renderLinkSource;

    private final ComponentSource componentSource;

    private final Response response;

    private final Authenticator authenticator;

    public AuthenticationFilter(PageRenderLinkSource renderLinkSource,
                                ComponentSource componentSource, Response response, Authenticator authenticator) {
        this.renderLinkSource = renderLinkSource;
        this.componentSource = componentSource;
        this.response = response;
        this.authenticator = authenticator;
    }

    public void handleComponentEvent(ComponentEventRequestParameters parameters,
                                     ComponentRequestHandler handler) throws IOException {

        if (dispatchedToAccessErrorPage(parameters.getActivePageName())) {
            return;
        }

        handler.handleComponentEvent(parameters);

    }

    public void handlePageRender(PageRenderRequestParameters parameters,
                                 ComponentRequestHandler handler) throws IOException {

        if (dispatchedToAccessErrorPage(parameters.getLogicalPageName())) {
            return;
        }

        handler.handlePageRender(parameters);
    }

    private boolean dispatchedToAccessErrorPage(String pageName) throws IOException {

        if (authenticator.isLoggedIn()) {
            // Logged user should not go back to Signin or Signup
           /* if (signinPage.equalsIgnoreCase(pageName) || signupPage.equalsIgnoreCase(pageName))
            {
                Link link = renderLinkSource.createPageRenderLink(defaultPage);
                response.sendRedirect(link);
                return true;
            }*/
            return false;
        }

        Component page = componentSource.getPage(pageName);

        if (!page.getClass().isAnnotationPresent(LoggedInUserAccess.class)) {
            return false;
        }

        Link link = renderLinkSource.createPageRenderLinkWithContext(AccessErrorPage.class, pageName);

        response.sendRedirect(link);

        return true;
    }
}
